package cn.z2huo.knowledge.concurrency.cas.lock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *
 * @author z2huo
 */
class ReentrantSpinLockTest {

    /**
     * 线程数量
     */
    private static final int THREAD_COUNT = 10;

    /**
     * 循环次数
     */
    private static final int TURNS = 1000000;

    private final ReentrantSpinLock lock = new ReentrantSpinLock();

    private static int sum = 0;

    public void increase() {
        lock.lock();
        try {
            sum++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        ReentrantSpinLockTest reentrantSpinLockTest = new ReentrantSpinLockTest();

        CountDownLatch countDownLatch = new CountDownLatch(THREAD_COUNT);

        Runnable runnable = () -> {
            for (int i = 0; i < TURNS; i++) {
                reentrantSpinLockTest.increase();
            }
            countDownLatch.countDown();
        };

        ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);

        long start, end;
        start = System.currentTimeMillis();

        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPool.execute(runnable);
        }

        try {
            // 等待所有线程执行完成，所有线程结束
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        end = System.currentTimeMillis();
        System.out.println("总耗时：" + (end - start) + " ms");
        System.out.println("累加结果为 " + sum);

        threadPool.close();
    }

}
